package com.competition.web.admin.log.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;

import com.competition.web.admin.log.IOperatorLog;
import com.competition.web.admin.service.ILogContentService;
import com.competition.web.admin.service.ILogService;
import com.basic.service.contract.IBaseService;
import com.competition.web.admin.util.SpringBeanUtil;
import com.competition.web.entity.Log;
import com.competition.web.entity.LogContentWithBLOBs;

public class DeleteLog extends AbstractLog implements IOperatorLog {

	@Override
	public Integer callBack(Object param, BoundSql boundSql, MappedStatement mappedStatement, Invocation invocation) {

		String tableName = this.getTableName(boundSql);

		if (this.recordLog(tableName)) {
			return 1;
		}

		Object[] object = this.parseData(param);

		// 标记是否已执行原来的方法
		int flag = 0;
		try {

			String serviceName = this.getServiceName(tableName);

			IBaseService<Object> baseService = SpringBeanUtil.getBean(serviceName);

			ILogService logService = SpringBeanUtil.getBean(ILogService.class);

			Integer[] integers = new Integer[object.length];

			for (int i = 0; i < object.length; i++) {
				
				// TODO
				integers[i] = Integer.valueOf(object[i].toString());
			}

			// 查出要删除的数据
			List<Object> data = baseService.getDataByIds(integers);

			int len = data.size();

			Log log;

			Class<?> target;

			Object toDelete;
			Object tableId;

			List<LogContentWithBLOBs> logContents = new ArrayList<>();
			for (int i = 0; i < len; i++) {

				log = new Log();

				toDelete = data.get(i);

				target = toDelete.getClass();

				tableId = this.getPropertyValue("id", target, toDelete);
				
				log.setTableId(Long.valueOf(tableId.toString()));

				logService.insertParse(log, tableName, (byte) 2);

				logContents.addAll(
						this.parseSingleData(target.getDeclaredFields(), tableName, target, toDelete, log.getId()));
			}

			ILogContentService logContentService = SpringBeanUtil.getBean(ILogContentService.class);

			logContentService.batchInsert(logContents.stream().toArray(LogContentWithBLOBs[]::new));

			// 执行原来的操作
			invocation.getMethod().invoke(invocation.getTarget(), invocation.getArgs());
			flag = 1;
			return 0;

		} catch (Exception e) {
			e.printStackTrace();
			return flag == 1 ? 1 : 0;
		}
	}

	protected LogContentWithBLOBs parseContentWithBLOBs(LogContentWithBLOBs content, Object oldValue, Object newValue) {

		content.setValue(newValue.toString());

		content.setCurrentValue("");

		return content;
	}
	
	protected String getTableName(BoundSql boundSql) {

		String sql = boundSql.getSql().toLowerCase();
		// update a set
		String updateTableSet = sql.substring(0, sql.indexOf("where"));

		return updateTableSet.replace("\n", "").replace("\t", "").replace("delete from", "").trim();

	}
}